declare namespace g = "ddi:group:3_1";
declare namespace dc="ddi:dcelements:3_1";
declare namespace d="ddi:datacollection:3_1"; 
declare namespace dc2="http://purl.org/dc/elements/1.1/"; 
declare namespace s="ddi:studyunit:3_1"; 
declare namespace c="ddi:conceptualcomponent:3_1";
declare namespace r="ddi:reusable:3_1"; 
declare namespace a="ddi:archive:3_1"; 
declare namespace ddi="ddi:instance:3_1"; 
declare namespace l="ddi:logicalproduct:3_1";

import module namespace request="http://exist-db.org/xquery/request";
import module namespace json="http://www.json.org";

declare option exist:serialize "method=json media-type=text/javascript";

(: if callback is defined :)
let $callback := request:get-parameter("callback", ())
let $lang     := request:get-parameter("lang", ())

let $s       := request:get-parameter("s", (''))
let $series  := request:get-parameter("series", ())

let $start   := xs:integer(request:get-parameter("start", "0"))
let $records := xs:integer(request:get-parameter("records", "10"))
let $action  := request:get-parameter("action","search")

let $collection := collection('/db/ddi/data/ddi3/internal')

(:filter on series when avalible:)
let $collection := if(empty($series)) 
	then
		$collection
	else
	 	$collection/ddi:DDIInstance/s:StudyUnit[contains(concat(',', $series, ','), concat(',', r:UserID[@type='series_id'], ','))]

let $result :=
	if(empty($lang))
	then
		$collection//s:StudyUnit[.//r:Title[ft:query(., $s)] or .//r:Content[ft:query(., $s)] or .//r:Creator[ft:query(., $s)]]
	else
                $collection//s:StudyUnit[.//r:Title[ft:query(.[@xml:lang=$lang], $s)] or .//r:Content[ft:query(.[@xml:lang=$lang], $s)] or .//r:Creator[ft:query(.[@xml:lang=$lang], $s)]]

(: compute the limits for this page :)
let $max := count($result)
let $start := 
      if ($action = "previous") 
      then max(($start - $records, 1))
      else if ($action="next")
      then  if ($max <$start +$records) 
            then $start 
            else $start +$records
      else if ($action="Search")
      then 1
      else $start
let $end :=  min (($start + $records ,$max))
 
(: restrict the full set of matches to this subsequence :)
let $matches := subsequence($result,$start,($end+1))

let $result :=
    for $s in $matches
        return <study>
                   <id>{fn:string($s/@id)}</id>
                   <title>
                    {                    
                            for $t in $s/r:Citation/r:Title
                                return element {$t/@xml:lang} {fn:string($t)}
                    }
                   </title>
                   <abstract>
                    {                    
                            for $a in $s/s:Abstract/r:Content
                                return element {$a/@xml:lang} {fn:string($a)}
                    }
                   </abstract>
                   <other-material>
                    {                    
                            for $l in $s/d:DataCollection/r:OtherMaterial/@xml:lang  
                                return element {$l}{
                                for $o in $s/d:DataCollection/r:OtherMaterial[@xml:lang = $l]
                                    return <link><url>{fn:string($o/r:ExternalURLReference)}</url><label>{xs:string($o/r:Citation/r:Title[@xml:lang = $l])}</label></link>
                                }
                    }
                   </other-material>
                   

                   <creators>
                    {       for $l in $s/r:Citation/r:Creator/@xml:lang                                
                                return element {$l}{
                                for $t in $s/r:Citation/r:Creator[@xml:lang = $l]
                                    return <person><val>{xs:string($t)}</val><affiliation>{xs:string($t/@affiliation)}</affiliation></person>
                                }
                    }
                   </creators>
               </study>

let $all := count($collection//s:StudyUnit)

let $output := <results>
                        <total>{$all}</total>
                        <hits>{$max}</hits>
                        <start>{$start}</start>
                        <end>{$end}</end>
                        <series>{$series}</series>
                        <studies>{$result}</studies>
                </results>

return $output